//
//  HistoryWorkController.m
//  PropertyMananger
//
//  Created by bh on 17/1/23.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "HistoryWorkController.h"
#import "PullDownMenu.h"
#import "MCSearchBar.h"
#import "PublicRepairCell.h"
#import "HydroRepairCell.h"
#import "PublicRepairModel.h"
#import "RepairDetailController.h"
#import "ComplainCell.h"
#import "HistoryModel.h"
#import "HydroRepairDetailController.h"
#import "ComplainDetailController.h"
#import "TimerSelectedView.h"

@interface HistoryWorkController ()<PullDownMenuDelegate,UISearchBarDelegate,UITextFieldDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate>


@property (nonatomic,strong) PullDownMenu * menu;

@property (nonatomic,retain) NSMutableArray *arr;

//选择查询类型
@property (nonatomic,strong) NSArray * typeArray;

//cell模块
@property (nonatomic,strong) NSArray * iconArr;//icon数据

//各种查询类型数据源
/**公共报修*/
@property (nonatomic,strong) NSMutableArray * publicRepiarArr;
/**水电报修*/
@property (nonatomic,strong) NSMutableArray * hydropowerArray;
/**投诉单*/
@property (nonatomic,strong) NSMutableArray * complainArray;

@property (nonatomic,strong) NSMutableArray * dataSoruce;//数据源

@property (nonatomic,strong) TimerSelectedView * timeSeletedView;
@property (nonatomic,copy) NSString * timeStr;//截取的系统时间
@property (nonatomic,copy) NSString * showTimeStr;//要显示的时间

@end

@implementation HistoryWorkController


- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self initTitleViewName:@"历史工单"];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 50, BHscreenW, BHscreenH - 50 - 64) isGroup:NO];
     self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;

    self.tableView.allowsSelection = YES;
    
    [self getYearData];
    
    [self setupUI];
    
   // [self setupSearchBar];
    
    [self createPlaceHolder];
    
    [self postQueryListData];

    
}
#pragma mark - 创建刷新UI
- (void)createRefresh{
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        self.isDown = YES;
        //获取数据
        [self postQueryListData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        [self postQueryListData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
    
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
}

#pragma mark - 下拉列表
- (void)setupUI
{
    self.typeArray = @[@[@"公共报修", @"水电报修",@"投诉单"]];
    self.menu = [[PullDownMenu alloc] init];
    self.menu.array = self.typeArray;
    self.menu.delegate = self;
    
    self.menu.frame = CGRectMake(0, 0, self.menu.frame.size.width, self.menu.frame.size.height);
    self.menu.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.menu];

    self.resultArr = [[NSMutableArray alloc]init];
    self.dataSoruce = [[NSMutableArray alloc]init];
    
    if (self.dataSoruce.count == 0) {
        
         self.tableView.mj_footer.hidden = YES;
    }
    
    //时间选择
    self.timeSeletedView = [[TimerSelectedView alloc]initWithFrame:CGRectMake(BHscreenW - 150, 0, 150, 50)];
    [self.menu addSubview:self.timeSeletedView];
    
       self.timeSeletedView.yearLabel.text = self.showTimeStr;
    
   [ self.timeSeletedView.monthButton addTarget:self action:@selector(selectedMonth:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView * bgView = [[UIView alloc] init];
    bgView.backgroundColor = BHGrayColor;
    [self.view addSubview:bgView];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.menu).with.offset(0);
        make.top.equalTo(self.menu.mas_bottom).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(BHscreenW,10));
    }];

    
}
- (void)selectedMonth:(UIButton *)button{

    DLog(@"点击选择时间");
     __block HistoryWorkController *weakSelf = self;
    dateTimePickerView = [[HcdDateTimePickerView alloc] initWithDatePickerMode:DatePickerYearMonthMode defaultDateTime:[[NSDate alloc]initWithTimeIntervalSinceNow:1000]];
    [self.view addSubview:dateTimePickerView];
    
    dateTimePickerView.topViewColor = BHGrayColor;
    dateTimePickerView.buttonTitleColor = Theme_Color;
    
    dateTimePickerView.clickedOkBtn = ^(NSString * datetimeStr){
        NSLog(@"%@", datetimeStr);
        
        
        NSArray * monthArray = [datetimeStr componentsSeparatedByString:@"-"];
        DLog(@"月份 == %@",monthArray[1]);
        
        if ([monthArray[1]integerValue] <=9) {
            
           weakSelf.timeSeletedView.yearLabel.text = [NSString stringWithFormat:@"%@年/0%@月",monthArray[0],monthArray[1]];
            weakSelf.timeStr = [NSString stringWithFormat:@"%@-0%@",monthArray[0],monthArray[1]];
        }else{
            
            weakSelf.timeSeletedView.yearLabel.text = [NSString stringWithFormat:@"%@年/%@月",monthArray[0],monthArray[1]];
            weakSelf.timeStr = [NSString stringWithFormat:@"%@-%@",monthArray[0],monthArray[1]];
        }

        weakSelf.isDown = YES;
       [weakSelf postQueryListData];
        
    };
    
    if (dateTimePickerView) {
        [self.view addSubview:dateTimePickerView];
        [dateTimePickerView showHcdDateTimePicker];
    }

}
#pragma mark - 搜索框
- (void)setupSearchBar
{
    self.searchBar = [[MCSearchBar alloc] initWithFrame:CGRectMake(80, 7.5, self.view.bounds.size.width - 90, 35) placeholder:nil];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入订单/投诉编号";
    self.searchBar.barTintColor = BHColor(237, 237, 237);
    [self.menu addSubview:self.searchBar];
    [self.searchBar setBackgroundColor:BHColor(237, 237, 237)];
    self.searchBar.layer.cornerRadius = 18.0f;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.borderWidth = 0.5;
    self.searchBar.layer.borderColor = BHColor(237, 237, 237).CGColor;
    self.searchBar.backgroundColor = BHColor(237, 237, 237);
    self.searchText = @"";
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
    UIView * lineView = [[UIView alloc]init];
    [self.tableView addSubview:lineView];
    lineView.backgroundColor = [BHColor(153, 153, 153)colorWithAlphaComponent:0.1];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).with.offset(0);
        make.top.equalTo(self.searchBar.mas_bottom).with.offset(7);
        make.size.mas_equalTo(CGSizeMake(BHscreenW, 10));
    }];
    
}
// 实现代理,选择查询方式
#pragma mark - PullDownMenuDelegate
- (void)PullDownMenu:(PullDownMenu *)pullDownMenu didSelectRowAtColumn:(NSInteger)column row:(NSInteger)row{
    
        [self.dataSoruce removeAllObjects];
        [self.resultArr removeAllObjects];
        [self.tableView reloadData];
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;

       self.queryType = row;
    
    self.isDown = YES;
    [self postQueryListData];
    [self.tableView.mj_header beginRefreshing];
    DLog(@"self.queryType === %ld",self.queryType);

    
}
#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

        if (self.isSearch) {
            return self.resultArr.count ;
        }else{
            if (self.queryType == 0) {
                
                 return self.dataSoruce.count;
                
            }else if (self.queryType == 1){
            
            return self.dataSoruce.count;
            }else if (self.queryType == 2){
            
               return self.dataSoruce.count;
            }
        }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.dataSoruce.count == 0){
        return nil;
    }
   
    DLog(@"%ld",indexPath.section);
    
    if (self.queryType == 0) {
         HistoryModel * model = self.dataSoruce[indexPath.section];
        PublicRepairCell * cell = [PublicRepairCell cellWithTableView:tableView];
        cell.orderProgressLable.hidden = YES;
        if (self.isSearch) {
            cell.orderCodeLabel.text = [NSString stringWithFormat:@"订单编号:%@",model.RepairCode];
            cell.repiarTypeLabel.text = model.CategoryName;
            cell.repiarAdressLabel.text = model.RepairAddr;
            cell.repiarManLabel.text = model.LinkMan;
            
        }else{
            cell.orderCodeLabel.text = [NSString stringWithFormat:@"订单编号:%@",model.RepairCode];
            cell.repiarTypeLabel.text = model.CategoryName;
            cell.repiarAdressLabel.text = model.RepairAddr;
            cell.repiarManLabel.text = model.LinkMan;
        }
        
        return cell;
 
    }else if (self.queryType == 1){
        
        HydroRepairCell * cell = [[HydroRepairCell alloc]init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        HistoryModel * model = self.dataSoruce[indexPath.section];
        cell.orderProgressLable.hidden = YES;

        if (self.isSearch) {
            cell.orderCodeLabel.text = [NSString stringWithFormat:@"订单编号:%@",model.RepairCode];
            cell.repiarTypeLabel.text = model.CategoryName;
            cell.repiarAdressLabel.text = model.RepairAddr;
            cell.repiarManLabel.text = model.LinkMan;
            cell.appointTimeLabel.text = model.AppointTime;
        }else{
            cell.orderCodeLabel.text = [NSString stringWithFormat:@"订单编号:%@",model.RepairCode];
            cell.repiarTypeLabel.text = model.CategoryName;
            cell.repiarAdressLabel.text = model.RepairAddr;
            cell.repiarManLabel.text = model.LinkMan;
            cell.appointTimeLabel.text = model.AppointTime;
            
        }

        return cell;
    }else if (self.queryType == 2){
        ComplainCell * cell = [ComplainCell cellWithTableView:tableView];
        HistoryComplainModel * model = self.dataSoruce[indexPath.section];
     //   cell.iconImg.hidden = YES;
        cell.orderProgressLable.hidden = YES;

        
        if (self.isSearch) {
            cell.complainCodeLabel.text = [NSString stringWithFormat:@"投诉编号:%@",model.ComplaintCode];
            cell.timeLabel.text = model.ComplaintTime;
            cell.contentLabel.text = model.Contents;
            cell.complianManLabel.text = model.ComplaintMan;
            
        }else{
            cell.complainCodeLabel.text = [NSString stringWithFormat:@"投诉编号:%@",model.ComplaintCode];
            cell.timeLabel.text = model.ComplaintTime;
            cell.contentLabel.text = model.Contents;
            cell.complianManLabel.text = model.ComplaintMan;
        }

        DLog(@"投诉单编号 === %@",model.ComplaintCode);
        return cell;
    
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.queryType == 0) {
        
        return 215;
        
    }else if (self.queryType == 1){
        
        return 265;
    }else if (self.queryType == 2){
    
        return 215;
    }

    return 215;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    DLog(@"%ld===%ld",indexPath.section,indexPath.row);
    if (self.queryType == 0) {
         DLog(@"点击公共详情");
        RepairDetailController * repairDetVC = [[RepairDetailController alloc]init];
        repairDetVC.model = self.dataSoruce[indexPath.section];
        [self.navigationController pushViewController:repairDetVC animated:YES];
        
    }else if (self.queryType == 1){
    DLog(@"点击水电详情");
        HydroRepairDetailController * hydroDetailVC = [[HydroRepairDetailController alloc]init];
        hydroDetailVC.model = self.dataSoruce[indexPath.section];
        [self.navigationController pushViewController:hydroDetailVC animated:YES];
    }else if (self.queryType == 2){
    
         DLog(@"点击投诉详情");
        ComplainDetailController * complainDetailVC = [[ComplainDetailController alloc]init];
        complainDetailVC.model = self.dataSoruce[indexPath.section];
        [self.navigationController pushViewController:complainDetailVC animated:YES];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

#pragma mark - 暂未图
- (void)createPlaceHolder
{
    
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_work_order"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无历史工单";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}
#pragma mark - 查询数据请求
- (void)postQueryListData{

    NSDictionary * parms = nil;


        if (self.queryType == 0) {//公共报修
          
                parms = @{
                          @"CommunityID":userModel.CommunityID,
                          @"Type":@"1",
                          @"Time":self.timeStr,
                          @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                          @"json":@"\{\"jsonEntity\":\{},\"action\":\"findmodebykey\",\"version\":\"V1.0\"}"
                          };

        }else if (self.queryType == 1){//水电报修
            
            parms = @{
                      @"CommunityID":userModel.CommunityID,
                      @"Type":@"2",
                      @"Time":self.timeStr,
                      @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                      @"json":@"\{\"jsonEntity\":\{},\"action\":\"findmodebykey\",\"version\":\"V1.0\"}"
                      };
            
        }else if (self.queryType == 2){//投诉
            
            parms = @{
                      @"CommunityID":userModel.CommunityID,
                      @"Type":@"3",
                      @"Time":self.timeStr,
                      @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                      @"json":@"\{\"jsonEntity\":\{},\"action\":\"findmodebykey\",\"version\":\"V1.0\"}"
                      };
            
        }
    
       DLog(@"提交的参数 === %@",parms);
    [WorkOrderRequest postOrderListQuerySuccess:^(id data) {
        if (self.isDown == YES) {
            
            self.isDown = NO;
    
           [self.dataSoruce removeAllObjects];
            
        }
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"历史工单查询的数据 == %@",array);
        if (self.queryType == 0 || self.queryType == 1) {
            
            for (NSDictionary * dict in array) {
                
                HistoryModel * model = [[HistoryModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                
                [self.dataSoruce addObject:model];
                DLog(@"self.dataSoruce == %@",self.dataSoruce);
                DLog(@"维修人员 == %@",model.ReplyMan);
            }

        }else if (self.queryType == 2){
        
            for (NSDictionary * dict in array) {
                
                HistoryComplainModel * model = [[HistoryComplainModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                
                [self.dataSoruce addObject:model];
                
                DLog(@"投诉人 == %@",model.ComplaintMan);
            }

        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        if (self.dataSoruce.count != 0) {
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
        }else{
        
         self.tableView.mj_footer.hidden = YES;
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        
        }
        
        if (self.dataSoruce.count >= 3) {
            
            [self createRefresh];
        }

        
        [self.tableView reloadData];
        
    } Fail:^(NSString *errorDes) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } param:parms];

}
#pragma mark - 获取系统时间
- (void)getYearData{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval time = [zone secondsFromGMTForDate:date];
    NSDate *dateNow = [date dateByAddingTimeInterval:time];
    NSString * timeDataStr = [NSString stringWithFormat:@"%@",dateNow];
    DLog(@" === %@",dateNow);
    
    NSArray * arr = [timeDataStr componentsSeparatedByString:@"-"];
    DLog(@"月份格式化 == %@",arr[1]);
    self.timeStr = [NSString stringWithFormat:@"%@-%@",arr[0],arr[1]];
   // DLog(@" === %@",self.timeStr);
    self.showTimeStr = [NSString stringWithFormat:@"%@年/%@月",arr[0],arr[1]];
    
}

@end
